import React, { useState } from "react";
import { Modal, Form, Row, Col, Radio, message, Upload, Button, UploadProps } from "antd";
import XlSelect from "@/components/Form/XlSelect";
import { UploadOutlined } from "@ant-design/icons";
import { useModel } from "@umijs/max";
import { modalPropsType } from "@/constants/types";
import { fetchSettlementWeeksByYear } from "@/pages/BasicInfo/services";
import { useComponentDidMount } from "@/hooks";

const {Item} = Form;
const rules = [{required: true, message: '此项必填'}];
const labelCol = {span: 4}
const initValue = {year: String(new Date().getFullYear())}

const LineQuoteImport = ({visible, onCancel, onSubmit, loading}: modalPropsType) => {
  const [form] = Form.useForm();
  const {getDict} = useModel('dictModel');
  const [weeks, setWeeks] = useState([]);

  const handleSubmit = async () => {
    const res = await form.validateFields();
    const formData = new FormData();
    formData.append('year', res?.year);
    formData.append('week', res?.week);
    formData.append('deliveryMethod', res?.deliveryMethod);
    formData.append('file', res?.file?.[0]?.originFileObj);
    onSubmit(formData);
  }

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  const yearChange = async (year: string) => {
    form.setFieldValue('week', undefined);
    const res = await fetchSettlementWeeksByYear({year});
    setWeeks((res?.map((v: string) => ({label: v, value: v}))));
  }

  useComponentDidMount(async () => {
    const res = await fetchSettlementWeeksByYear({year: initValue.year});
    setWeeks((res?.map((v: string) => ({label: v, value: v}))));
  })

  return (
    <Modal
      open={visible}
      maskClosable={false}
      confirmLoading={loading}
      width="650px"
      title="导入报价"
      onCancel={onCancel}
      onOk={handleSubmit}
    >
      <Form form={form} labelCol={labelCol} initialValues={initValue} style={{marginTop: 20, marginBottom: 20}}>
        <Row gutter={20}>
          <Col span={12}>
            <Item label="年份" name="year" rules={rules} labelCol={{span: 8}}>
              <XlSelect style={{width: 200}} onChange={yearChange} options={getDict('year')} />
            </Item>
          </Col>
          <Col span={12}>
            <Item label="周次" name="week" rules={rules} labelCol={{span: 8}}>
              <XlSelect style={{width: 200}} options={weeks} />
            </Item>
          </Col>
        </Row>
        <Item label="报价模板" name="deliveryMethod" rules={rules}>
          <Radio.Group options={getDict('deliveryMethod')} />
        </Item>
        <Item label="导入报价" name="file" valuePropName="fileList" getValueFromEvent={normFile} rules={rules}>
          <Upload maxCount={1} beforeUpload={() => false}>
            <Button style={{width: 200, height: 30}} icon={<UploadOutlined />}>点击上传</Button>
          </Upload>
        </Item>
      </Form>
    </Modal>
  );
}
export default LineQuoteImport;